package src.Client;

import java.awt.event.ActionEvent;
import java.io.*;
import java.net.*;
import src.User.User;
import src.common.MessageType;
import src.common.impl.Message;
import src.Client.*;

public class YYChatClientConnection {
    public static Socket s;
    public YYChatClientConnection () {
        try {
            s=new Socket("127.0.0.1",3456);//创建Socket对象,和服务器建立
            System.out.println("客户端连接成功:"+s);
        } catch (IOException e) {
            e.printStackTrace () ;

        }

    }

    public Message loginValidate(User user) {
        Message msg = null;
        try {
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);

            oos.writeObject(user);
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            msg = (Message) ois.readObject();
            if (msg.getMessageType().equals(MessageType.LOGIN_SUCCESS)){
                new ClientReceiverThread(s).start();
            }else {
                s.close();
            }
        }catch (IOException e){
            e.printStackTrace() ;
        }catch (ClassNotFoundException e){
            e.printStackTrace() ;
        }
        return msg;
    }

    public boolean registerUser(User user) {
        boolean success=false;
        try {
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(user);
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            Message message = (Message) ois.readObject();
            if (message.getMessageType().equals(MessageType.USER_REGISTER_SUCCESS)){
                success=true;
                new ClientReceiverThread(s).start();
            }
            s.close();
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace() ;
        }

        return success;
    }

    public Message loginByPhone(User user) {
        Message msg = null;
        try {
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);

            oos.writeObject(user);
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            msg = (Message) ois.readObject();
            if (msg.getMessageType().equals(MessageType.LOGIN_SUCCESS)){
                new ClientReceiverThread(s).start();
            }else {
                s.close();
            }
        }catch (IOException e){
            e.printStackTrace() ;
        }catch (ClassNotFoundException e){
            e.printStackTrace() ;
        }
        return msg;
    }
}